package com.atguigu.yygh.msm.controller;

import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author jiaoyanlin
 * @Date 2021/9/8 9:50
 * @Description MsmController
 */
@RestController
@RequestMapping("/api/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //发送验证码的方法
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        //1.先根据手机号 去redis查询 有没有数据  如果有 就直接返回登录数据
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(redisCode)){
            return R.ok();
        }
        //2.发送验证码
        String code = RandomUtil.getFourBitRandom();
        boolean flag = msmService.sendMsmDx(phone,code);
        //3.判断是否成功  成功 验证码存到redis
        if (flag){
            redisTemplate.opsForValue().set(phone,code,500, TimeUnit.SECONDS);
            return R.ok();
        }else {
            return R.error();
        }

    }
}
